import { defineStore } from 'pinia';
import { ref } from 'vue';
import { monitoringForceList, getMonitoringForce } from '@/api/monitoringForce';
import { MonitoringEquipment } from '@/constants/components/MonitoringEquipment';
import potencyIcon from '@/assets/largescreen/potency-icon.png';
import pressureIcon from '@/assets/largescreen/pressure-icon.png';
import flowIcon from '@/assets/largescreen/flow-icon.png';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';
import type { moduleInfo } from '@/utils/mapBackendData';
import { MapDeviceTypes } from '@/enums/MapDeviceTypesEnum';
import { useDialogStore } from '@/store/modules/useDialogStore';
import icon1 from '@/assets/largescreen/guanxian-mokuai.png';
import icon2 from '@/assets/largescreen/renkoumijiqu-mokuai.png';
import icon3 from '@/assets/largescreen/ranqichangzhan-mokuai.png';
import icon4 from '@/assets/largescreen/dixiaxianglinkongjian-mokuai.png';

export const useMonitoringEquipmentStore = defineStore('monitoringEquipment', () => {
  const monitoringForceData = ref<moduleInfo[]>(MonitoringEquipment);
  const { addPoint, clearAllPoints } = useCesiumPoints();
  const dataSource = reactive<Record<string, any[]>>({});
  const sceneNameList = ref<string[]>([]); // 用于存储场景名称的数组来进行判断高亮
  const currentDeviceType = ref(''); //保存一个当前设备类型 给弹窗列表使用
  const currentDeviceName = ref(''); //保存一个当前设备名称 给弹窗列表使用
  const { flyTo } = useDialogStore();
  const currentDeviceList = ref({
    '01': {
      '相邻地下空间': {
        id: 0,
        icon: icon1,
        list: []
      },
      '餐饮场所': {
        id: 1,
        icon: icon2,
        list: []
      },
      '人口密集区主干管线': {
        id: 2,
        icon: icon3,
        list: []
      },
      '其他': {
        id: 3,
        icon: icon4,
        list: []
      }
    },
    '02': {
      '人口密集区主干管线': {
        id: 0,
        icon: icon3,
        list: []
      }
    },
    '03': {
      '门站': {
        id: 0,
        icon: icon4,
        list: []
      },
      '调压站': {
        id: 1,
        icon: icon4,
        list: []
      },
      'LNG调峰站': {
        id: 2,
        icon: icon4,
        list: []
      },
      '重点工商业户站': {
        id: 3,
        icon: icon4,
        list: []
      }
    }
  }); //保存一个当前设备列表 给弹窗列表使用
  const currentBigName = ref(''); //保存一个当前设备大类名称 给弹窗列表使用
  const { openDialog } = useDialogStore();
  const getPic = computed(() => {
    return (index: number) => {
      return index === 0 ? potencyIcon : index === 1 ? pressureIcon : flowIcon;
    };
  });
  //获取入户监测组件实例
  const userMonitoringRef = ref();
  const visible = ref(false);
  const userMonitoringHandle = () => {
    visible.value = !visible.value;
    userMonitoringRef.value.getList();
  };
  const close = () => {
    visible.value = false;
  };
  /**
   * 切换设备实体
   */
  const toggleEquipmentEntities = async (scene: string, type: string, name: string) => {
    flyTo({ longitude: 117.140035075, latitude: 36.798747059 }, 400000);
    const newName = scene + name;
    currentBigName.value = name;
    currentDeviceType.value = type;
    currentDeviceName.value = scene;
    if (dataSource[newName]) {
      clearAllPoints(dataSource[newName]);
      sceneNameList.value = sceneNameList.value.filter((item) => item !== newName);
      delete dataSource[newName];
    } else {
      const { data } = await getMonitoringForce({
        type,
        scene: scene === 'LNG调峰站' ? '调峰储备站' : scene
      });
      currentDeviceList.value[type][scene].list = data;
      sceneNameList.value = [...sceneNameList.value, newName];
      openDialog('monitoringEquipmentModule');
      dataSource[newName] = await data.map((point) => addPoint(point, scene, MapDeviceTypes(point.monitorType)));
    }
  };
  //清除全部点位
  const initClearAllPoints = () => {
    for (const key in dataSource) {
      clearAllPoints(dataSource[key]);
      delete dataSource[key];
    }
    sceneNameList.value = [];
  };
  const fetchMonitoringData = async () => {
    try {
      // 使用Promise.all并行请求
      const [forceRes, pressureRes, flowRateRes] = await Promise.all([
        monitoringForceList({ type: '01' }),
        monitoringForceList({ type: '02' }),
        monitoringForceList({ type: '03' })
      ]);

      // 更新数据
      monitoringForceData.value = [
        { ...monitoringForceData.value[0], ...forceRes.data },
        { ...monitoringForceData.value[1], ...pressureRes.data },
        { ...monitoringForceData.value[2], ...flowRateRes.data }
      ];

      console.log('Monitoring data loaded:', monitoringForceData.value);
    } catch (error) {
      console.error('Failed to fetch monitoring data:', error);
    }
  };
  
  return {
    monitoringForceData,
    getPic,
    userMonitoringRef,
    visible,
    sceneNameList,
    currentDeviceType,
    currentDeviceName,
    currentDeviceList,
    currentBigName,
    userMonitoringHandle,
    close,
    fetchMonitoringData,
    toggleEquipmentEntities,
    initClearAllPoints
  };
});
